﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using SpectationClient.DataBaseDescription;
//using SpectationClient.SpectralTools;
using Npgsql;
using SpectationClient;
using SpectationClient.Stuff;
using SpectationClient.SpectralTools;
using SpectationClient.SQLCommandBuilder;

namespace SpectationClient.GUI {
    public partial class SubInsertBaseInfo : Form {
        private DBManager dbm;
        private ErrorList CAMP_EL, SENS_EL, WREF_EL, OP_EL, CAMERA_EL;

        //private PostGIS_Npgsql_CommandBuilder CMB = new PostGIS_Npgsql_CommandBuilder();
        public SubInsertBaseInfo(ref DBManager DBM) {
            InitializeComponent();

            this.Icon = Resources.Icon;
            this.dbm = DBM;

            this.SENS_EL = new ErrorList(EP, ref SENS_btINSERT);
            this.SENS_SName.DataSource = Enum.GetNames(typeof(Spectrum.InstrumentType));
            //DataSource =  .InstrumentTypegetMAP_Table_InstrumentTypes("VALUES", "DISPLAY", true);
            //this.SENS_SName.DisplayMember = "DISPLAY";
            //this.SENS_SName.ValueMember = "DISPLAY";
            this.SENS_SName.TextChanged +=new EventHandler(SENS_VAL_Required);
            this.SENS_SSerial.TextChanged += new EventHandler(SENS_VAL_Required);
            this.SENS_SCalNo.TextChanged += new EventHandler(SENS_VAL_Required);
            this.SENS_btINSERT.Enabled = false;

            this.WREF_EL = new ErrorList(EP, ref WREF_INSERT_BTN);
            this.WREF_INSERT_BTN.Enabled = false;
            //TODO: this.WREF_Name.DataSource = DBM.getMAP_Table("CORE","WREF_PANELS","ID",,true)
            this.WREF_Name.TextChanged += new EventHandler(WREF_VAL_Required);
            this.WREF_CAL.TextChanged += new EventHandler(WREF_VAL_Required);
            this.WREF_CAL.TextChanged += new EventHandler(WREF_VAL_Required);
            this.WREF_ID.TextChanged += new EventHandler(WREF_VAL_Required);
            this.WREF_CALFILE_TB.TextChanged += new EventHandler(WREF_VAL_Required);
            

            this.CAMP_EL = new ErrorList(EP, ref CAMP_Insert_bt);
            //this.CAMP_EL.ErrorAdded += new EventHandler(CAMP_EL_ErrorAdded);
            //this.CAMP_EL.ErrorListIsEmpty += new EventHandler(CAMP_EL_ErrorListIsEmpty);    
            this.CAMP_End.ValueChanged += new EventHandler(CAMP_VAL_Required);
            this.CAMP_Begin.ValueChanged += new EventHandler(CAMP_VAL_Required);
            this.CAMP_Name.TextChanged += new EventHandler(CAMP_VAL_Required);
            this.CAMP_Area.TextChanged += new EventHandler(CAMP_VAL_Required);
            this.CAMP_Insert_bt.Enabled = false;


            
            this.CAMERA_EL = new ErrorList(EP, ref CAMERA_INSERT_BT);
            //this.CAMERA_EL.ErrorAdded += new EventHandler(CAMERA_EL_ErrorAdded);
            //this.CAMERA_EL.ErrorListIsEmpty += new EventHandler(CAMERA_EL_ErrorListIsEmpty);
            this.CAMERA_INSERT_BT.Enabled = false;
            this.CAMERA_NAME_TB.TextChanged += new EventHandler(CAMERA_VAL_Required);
            this.CAMERA_OWNER_TB.TextChanged += new EventHandler(CAMERA_VAL_Required);

            this.OP_EL = new ErrorList(EP, ref OP_INSERT_BT);
            //this.OP_EL.ErrorAdded += new EventHandler(OP_EL_ErrorAdded);
            //this.OP_EL.ErrorListIsEmpty += new EventHandler(OP_EL_ErrorListIsEmpty);
            this.OP_INSERT_BT.Enabled = false;
            this.OP_INSTITUTE_TB.TextChanged += new EventHandler(OP_VAL_Required);
            this.OP_NAME_TB.TextChanged += new EventHandler(OP_VAL_Required);
            this.OP_SURNAME_TB.TextChanged += new EventHandler(OP_VAL_Required);
        }
        private void WREF_VAL_Required(object sender, EventArgs e) { 
            //required
            WREF_EL.validation_string(WREF_Name, true);
            WREF_EL.validation_string(WREF_ID, true);
            WREF_EL.validation_Int32(WREF_CAL, true);
            //optional
            WREF_EL.validation_filepath(WREF_CALFILE_TB, WREF_CALFILE_TB.Tag, false);
        }
        private void OP_VAL_Required(object sender, EventArgs e) {
            //required
            OP_EL.validation_string(OP_SURNAME_TB, true);
            OP_EL.validation_string(OP_NAME_TB, true);
            OP_EL.validation_string(OP_INSTITUTE_TB, true);
            //optional
            //workgroup, notes
        }
        private void CAMERA_VAL_Required(object sender, EventArgs e) {
            //required
            CAMERA_EL.validation_string(CAMERA_NAME_TB, true);
            CAMERA_EL.validation_string(CAMERA_OWNER_TB, true);
            //optional
        }

        private void SENS_VAL_Required(object sender, EventArgs e) {
            //required    
            SENS_EL.validation_Int32(SENS_SCalNo, true);
            SENS_EL.validation_string(SENS_SName, true);
            SENS_EL.validation_string(SENS_SSerial, true);
    
            //optional
            SENS_EL.validation_filepath(SENS_SCalFilePath, SENS_SCalFilePath.Tag, false);
            SENS_EL.validation_string(SENS_SNotes, false);
            SENS_EL.validation_DateTime(ref SENS_SCalDate, false);
        }

        private void CAMP_VAL_Required(object sender, EventArgs e) {
            //required
            CAMP_EL.validation_string(CAMP_Name, true);
            CAMP_EL.validation_string(CAMP_Area, true);
            //optional
            CAMP_EL.validation_DateTime(ref CAMP_Begin, false);
            CAMP_EL.validation_DateTime(ref CAMP_End, false);
            if(CAMP_Begin.Checked && CAMP_End.Checked) {
                CAMP_EL.validation_DateBeginEnd(ref CAMP_Begin, ref CAMP_End, false, ErrorList.TimeMode.DayofYear);
            }
            
        }

        private void bt_ReadSerialAndCalNo_Click(object sender, EventArgs e) {
            OFD.Title = "Mit dem Sensor erstellte ASD-Datei auswählen";
            OFD.Multiselect = false;
            if (OFD.ShowDialog() == DialogResult.OK) {
                FileInfo fi = new FileInfo(OFD.FileName);
                Byte[] BA = File.ReadAllBytes(OFD.FileName);
                if(ASD_Reader.isValidASDSpectrum(BA)){
                    this.SENS_SSerial.Text = ASD_Reader.getInstrumentNo(BA).ToString();
                    this.SENS_SCalNo.Text = ASD_Reader.getCalibrationNo(BA).ToString();
                    String s = ASD_Reader.getInstrumentTypeString(BA);
                    this.SENS_SName.SelectedItem = s;
                }                
            }
        }

        private void SENS_btINSERT_Click(object sender, EventArgs e) {
                DataTable dt = dbm.getEmptyTable("CORE", "SENSORS");
                TableInfo ti = dbm.getTableInfo("CORE", "SENSORS");
                ColumnInfoSpectralFile sci = (ColumnInfoSpectralFile)ti["file"];
                DataRow dr = dt.NewRow();
                if (SENS_SCalDate.Checked) dr["cal_date"] = SENS_SCalDate.Value.Date;
                dr["name"] = SENS_SName.Text;
                dr["device_id"] = SENS_SSerial.Text;
                dr["cal_no"] = Int32.Parse(SENS_SCalNo.Text);
         
                //Optional
                FileInfo fi = SENS_SCalFilePath.Tag as FileInfo;
                if (fi != null && fi.Exists) {
                        sci.addFileValues(fi, dr);
                }

                dr["notes"] = SENS_SNotes.Text;
                if(insertDataRow(ti, dr)) {
                    //clear 
                    SENS_SCalNo.Text = "";
                    SENS_SCalFilePath.Tag = null;
                    SENS_SCalFilePath.Text = "";
                    SENS_SSerial.Text = null;
                    SENS_SName.SelectedIndex = 0;
                    SENS_SNotes.Text = "";
                    MessageBox.Show("Der Sensor wurde erfolgreich in die Datenbank eingefügt", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
        }

        private void WREF_INSERT_BTN_Click(object sender, EventArgs e) {
                DataTable dt = dbm.getEmptyTable("CORE", "WREF_PANELS");
                TableInfo ti = dbm.getTableInfo("CORE", "WREF_PANELS");
                ColumnInfoSpectralFile sci = (ColumnInfoSpectralFile)ti["file"];
                DataRow dr = dt.NewRow();
                //required
                dr["name"] = WREF_Name.Text;
                dr["device_id"] = WREF_ID.Text;
                dr["cal_no"] = Int32.Parse(WREF_CAL.Text);
        
                //optional
                if(WREF_CALDAT_DTP.Checked) dr["cal_date"] = WREF_CALDAT_DTP.Value.Date;
                FileInfo fi = WREF_CALFILE_TB.Tag as FileInfo;
                if(fi != null && fi.Exists){
                    sci.addFileValues(fi, dr);
                }

                if(WREF_DESCR_TB.Text.Trim().Length > 0) dr["notes"] = WREF_DESCR_TB.Text.Trim();
                if(this.insertDataRow(ti, dr)) {
                    MessageBox.Show("Daten erfolgreich eingefügt", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //clean
                    WREF_CAL.Text = WREF_CALFILE_TB.Text  = WREF_DESCR_TB.Text =
                    WREF_ID.Text = WREF_Name.Text = null;
                    WREF_CALFILE_TB.Tag = null;
                }
        }

       
        private void FilePathbtn_Click(object sender, EventArgs e) {
            OFD.Title = "Datei mit Kalibrationsspektrum des Sensors angeben";
            OFD.Multiselect = false;
            if(OFD.ShowDialog() == DialogResult.OK){
                SENS_SCalFilePath.Text = OFD.SafeFileName;
                SENS_SCalFilePath.Tag = new FileInfo(OFD.FileName);
            }
        }

        private void WREF_setFileBt_Click(object sender, EventArgs e) {
            OFD.Title = "Datei mit Kalibrationsspektrum des Spektralons angeben";
            OFD.Multiselect = false;
            if(OFD.ShowDialog() == DialogResult.OK) {
                WREF_CALFILE_TB.Text = OFD.SafeFileName;
                WREF_CALFILE_TB.Tag = new FileInfo(OFD.FileName);
            }
        }

        private DataRow removeEmptyValues(DataRow r) {
            for (int i = 0; i < r.ItemArray.Length; i++) {
                if (r[i].ToString().Trim().Length == 0) r[i] = DBNull.Value;
            }
            return r;
        }

        private bool insertDataRow(TableInfo ti, DataRow dr) {
            bool ret = false;
            InsertValues v = new InsertValues(ref ti);
            foreach(DataColumn c in dr.Table.Columns) {
                v.Add(c.ColumnName, dr[c]);
            }
            NpgsqlCommand cmd = v.getInsertCmd();
            cmd.Connection = this.dbm.Connection;
            cmd.Connection.Open();
            NpgsqlTransaction trans = cmd.Connection.BeginTransaction();
            try {
                cmd.ExecuteNonQuery();
                trans.Commit();
                ret = true;
            } catch(Exception ex) {
                trans.Rollback();
                cmd.Connection.Close();
                MessageBox.Show(TextHelper.Exception2String(ex), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } finally {
                cmd.Connection.Close();
            }
            return ret;
        }



        private void CAMP_Insert_Click(object sender, EventArgs e) {
            TableInfo ti = dbm.getTableInfo("CORE","CAMPAIGNS");
            DataTable dt = dbm.getEmptyTable("CORE", "CAMPAIGNS");
            DataRow dr = dt.NewRow();
            dr["name"] = CAMP_Name.Text;
            dr["area"] = CAMP_Area.Text;
            if(CAMP_Begin.Checked) dr["from"] = CAMP_Begin.Value.Date;
            if(CAMP_End.Checked) dr["until"] = CAMP_End.Value.Date;
            dr["notes"] = CAMP_Notes.Text;
            if(this.insertDataRow(ti, dr)) {
                MessageBox.Show("Daten erfolgreich eingefügt", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //clean all
                CAMP_Name.Text = CAMP_Area.Text = CAMP_Notes.Text = null;
                CAMP_End.Checked = CAMP_Begin.Checked = false;
            }
            
        }

        private void OP_INSERT_BT_Click(object sender, EventArgs e) {
            TableInfo ti = dbm.getTableInfo("CORE", "OPERATORS");
            DataTable dt = dbm.getEmptyTable("CORE", "OPERATORS");
            DataRow dr = dt.NewRow();
            //required
            dr["forename"] = OP_NAME_TB.Text;
            dr["surname"] = OP_SURNAME_TB.Text;
            dr["institute"] = OP_INSTITUTE_TB.Text;
            //optional
            dr["workgroup"] = OP_WORKGROUP_TB.Text;
            dr["notes"] = OP_DESCR_TB.Text;
            if(this.insertDataRow(ti, dr)) {
                MessageBox.Show("Daten erfolgreich eingefügt", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //clean
                OP_NAME_TB.Text = OP_SURNAME_TB.Text = OP_INSTITUTE_TB.Text = 
                OP_WORKGROUP_TB.Text = OP_DESCR_TB.Text = null;
            }
        }

        private void CAMERA_INSERT_BT_Click(object sender, EventArgs e) {
            TableInfo ti = dbm.getTableInfo("CORE", "CAMERAS");
            DataTable dt = dbm.getEmptyTable("CORE", "CAMERAS");
            DataRow dr = dt.NewRow();
            //required
            dr["name"] = CAMERA_NAME_TB.Text;
            dr["owner"] = CAMERA_OWNER_TB.Text;
            //optional
            dr["notes"] = CAMERA_DESCR_TB.Text;
            if(this.insertDataRow(ti, dr)) {
                MessageBox.Show("Daten erfolgreich eingefügt", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //clean
                CAMERA_DESCR_TB.Text = CAMERA_OWNER_TB.Text = CAMERA_NAME_TB.Text = null;
            }

        }


 
     
    }
}
